#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

// Father process -> read  -> fd[0]
// Child  process -> write -> fd[1]
int main()
{
    // 1.创建管道
    int fds[2] = {0};
    int n = pipe(fds); // fds:输出型参数
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "fd[0]:" << fds[0] << std::endl; // fd[0]:3
    std::cout << "fd[1]:" << fds[1] << std::endl; // fd[1]:4

    // 2.创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        std::cerr << "fork error" << std::endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程
        // 3.关闭不需要的fd, 关闭read
        ::close(fds[0]);

        int cnt = 0;
        int total = 0;
        while (true)
        {
            std::string message = "H";
            message += std::to_string(getpid());
            message += ", ";
            message += std::to_string(cnt);

            // fd[1]
            total += ::write(fds[1], message.c_str(), message.size());
            cnt++;
            std::cout << "total: " << total << std::endl;
            sleep(1);
        }
        exit(0);
    }
    else
    {
        // 父进程
        // 3.关闭不需要的fd, 关闭write
        ::close(fds[1]);

        char buffer[1024];
        while (true)
        {
            sleep(1);

            ssize_t n = ::read(fds[0], buffer, 1024);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "child->father, message:" << buffer << std::endl;
            }
            else if (n == 0)
            {
                // 当读到文件末尾时: 说明子进程的写端关闭, 此时父进程的读端读取数据无意义
                std::cout << "n: " << n << std::endl;
                std::cout << "child quit after father quit too" << std::endl;
                break;
            }
            else
            {
                // 读取错误...
            }

            // 父进程读端关闭, 此时子进程写入数据无意义, 操作系统直接杀掉子进程
            ::close(fds[0]);
            break;
        }
        int status = 0;
        pid_t rid = waitpid(id, &status, 0);
        std::cout << "father wait child success:" << rid;

        std::cout << " exit code: " << ((status >> 8) & 0xFF);
        std::cout << " exit signal: " << (status & 0x7F) << std::endl;
    }

    return 0;
}